package com.example.musicdemo.ui.fragment

import android.Manifest
import android.content.pm.PackageManager
import android.database.Cursor
import android.view.View
import android.view.ViewGroup
import android.widget.AbsListView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.app.ActivityCompat
import com.example.musicdemo.R
import com.example.musicdemo.adapter.VBangAdapter
import com.example.musicdemo.base.BaseFragment
import com.example.musicdemo.internal.collection.MusicCollection
import com.example.musicdemo.model.Music
import com.example.musicdemo.ui.activity.AudioPlayActivity
import com.example.musicdemo.util.PinyinComparator
import com.example.musicdemo.widget.SideBar
import kotlinx.android.synthetic.main.fragment_vbang.*
import org.jetbrains.anko.noButton
import org.jetbrains.anko.support.v4.alert
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.yesButton
import java.util.*
import kotlin.collections.ArrayList

class VBangFragment : BaseFragment(), MusicCollection.MusicCallbacks {
    private lateinit var mCollection: MusicCollection
    private lateinit var mAdapter: VBangAdapter
    private var sideBar: SideBar? = null
    private var dialog: TextView? = null
    private var title: TextView? = null
    private var titleLayout: LinearLayout? = null
    private var mList: ArrayList<Music> = ArrayList()
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private var pinyinComparator: PinyinComparator? = null

    /**
     * 上次第一个可见元素，用于滚动时记录标识。
     */
    private var lastFirstVisibleItem = -1

    override fun initView(): View? {
        return View.inflate(context, R.layout.fragment_vbang, null)
    }

    override fun initListener() {
        super.initListener()
        pinyinComparator = PinyinComparator() //汉语拼 音
        sideBar = activity?.findViewById<View>(R.id.sidebar) as SideBar
        dialog = activity?.findViewById<View>(R.id.floating_header) as TextView
        titleLayout = activity?.findViewById<View>(R.id.title_layout) as LinearLayout //标题
        title = activity?.findViewById<View>(R.id.title_layout_catalog) as TextView //标题
        mAdapter = VBangAdapter(context,ArrayList())
        Collections.sort(mList, pinyinComparator) //排列

        lvVBang.adapter = mAdapter
        initSideBar()
        //设置点击事件
        initListView()
        lvVBang.setOnItemClickListener { _, _, position, l ->

            //位置position
            //跳转到音乐播放界面

            startActivity<AudioPlayActivity>("list" to mList, "position" to position)
        }

    }

    override fun initData() {
        //动态权限申请
        handlePermission()
    }

    private fun initListView(){
        lvVBang?.setOnScrollListener(object : AbsListView.OnScrollListener{
            //上推标题。可用可不用
            override fun onScrollStateChanged(view: AbsListView, scrollState: Int){}
            override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int){
                if (mList.size > 1){
                    val section: Int? = getSectionForPosition(firstVisibleItem)
                    val nextSection: Int? = getSectionForPosition(firstVisibleItem + 1)
                    val nextSecPosition: Int? = nextSection?.let { getPositionForSection(it) }
                    if (firstVisibleItem != lastFirstVisibleItem){
                        val params = titleLayout?.layoutParams as ViewGroup.MarginLayoutParams
                        params.topMargin = 0
                        titleLayout?.layoutParams = params
                        title?.text = mList[section?.let { getPositionForSection(it) }!!].sortLetters
                    }
                    if (nextSecPosition == firstVisibleItem + 1){
                        val childView = view.getChildAt(0)
                        if (childView != null){
                            val titleHeight = titleLayout?.height
                            val bottom = childView.bottom
                            val params = titleLayout?.layoutParams as ViewGroup.MarginLayoutParams
                            if (bottom < titleHeight!!){
                                val pushedDistance = (bottom - titleHeight).toFloat()
                                params.topMargin = pushedDistance.toInt()
                                titleLayout?.layoutParams = params
                            } else {
                                if (params.topMargin != 0){
                                    params.topMargin = 0
                                    titleLayout?.layoutParams = params
                                }
                            }
                        }
                    }
                    lastFirstVisibleItem = firstVisibleItem
                }
            }
        })
    }


    private fun initSideBar(){
        sideBar?.setTextView(dialog!!)
        sideBar?.setOnTouchingLetterChangedListener(object :
            SideBar.OnTouchingLetterChangedListener {
            //右边的a b c d
            override fun onTouchingLetterChanged(s: String){
                // 该字母首次出现的位置
                val position = mAdapter?.getPositionForSection(s[0].code)
                if (position != -1){
                    position?.let { lvVBang?.setSelection(it) }
                }
            }
        })
    }

    /**
     *
     */
    private fun handlePermission() {
        val permission = Manifest.permission.READ_EXTERNAL_STORAGE
        //查看是否有权限
        val checkSelfPermission =
            context?.let { ActivityCompat.checkSelfPermission(it, permission) }
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
            loadSongs()
        } else {
            if (activity?.let {
                    ActivityCompat.shouldShowRequestPermissionRationale(
                        it,
                        permission
                    )
                } == true) {
                alert("我们只会访问音乐文件", "温馨提醒") {
                    yesButton { myRequestPermission() }
                    noButton { }
                }.show()

            } else {
                myRequestPermission()
            }
        }
    }

    /**
     * 加载音乐
     */
    private fun loadSongs() {
        mCollection = MusicCollection()
        this.activity?.let { mCollection.onCreate(it, this) }
        mCollection.loadMusic()
    }


    /**
     * 接受权限授权结果
     * requestCode 请求码
     * permissions 权限申请数组
     * grantResults 申请之后结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loadSongs()
        }
    }


    /**
     * 真正申请权限
     */
    private fun myRequestPermission() {
        val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        requestPermissions(permissions, 1)
    }

    override fun onMusicLoad(cursor: Cursor?) {

        //这已经回到了主线程
        mList = Music.getMusicBeans(cursor)
        Collections.sort(mList, pinyinComparator) //排列
        mAdapter.mList = mList
        mAdapter.notifyDataSetChanged()

        println("我要看看mlist是什么 $mList")
    }

    override fun onMusicReset() {
    }


    override fun onDestroyView() {
        super.onDestroyView()
        mCollection.onDestroy()
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    fun getSectionForPosition(position: Int): Int? {
        if (mList.isEmpty()) return 0
        if (mList.size<position) return 0
        if (mList[position].sortLetters?.isEmpty()!!) return 0
        return mList[position].sortLetters?.get(0)?.code?.toByte()?.toInt()
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    fun getPositionForSection(section: Int): Int {
        if (mList.isEmpty()) return 0
        for (i in mList.indices) {
            val sortStr: String? = mList[i].sortLetters
            if (sortStr?.isEmpty() == true) return 0
            val firstChar = sortStr?.uppercase(Locale.getDefault())?.get(0)
            if (firstChar?.code?.toByte()?.toInt() == section) {
                return i
            }
        }
        return -1
    }

}